package com.YHVision.qiuzhike.service.impl;

import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.model.entity.Question;
import com.YHVision.qiuzhike.service.QuestionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.mapper.QuestionThumbMapper;
import com.YHVision.qiuzhike.model.entity.QuestionThumb;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.service.QuestionThumbService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 题目点赞服务实现
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@Service
public class QuestionThumbServiceImpl extends ServiceImpl<QuestionThumbMapper, QuestionThumb> implements QuestionThumbService {

    @Resource
    private QuestionService questionService;


    /**
     * 题目点赞
     *
     * @param questionId
     * @param loginUserId
     * @return
     */
    @Override
    public int doQuestionThumb(long questionId, User loginUserId) {
        //获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //获取登录用户id
        Long userId = loginUserId.getId();
        //串行点赞
        QuestionThumbService questionThumbService =(QuestionThumbService) AopContext.currentProxy();
        synchronized (String.valueOf(userId).intern()){
            return questionThumbService.doQuestionThumbInner(questionId, userId);
        }

    }

    /**
     * 封装事务方法
     * 题目点赞具体操作（内部操作）
     *
     * @param userId
     * @param questionId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doQuestionThumbInner(long questionId, long userId) {
        //数据校验
        if (questionId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR," 题目id或用户id不存在");
        }
        QuestionThumb questionThumb = new QuestionThumb();
        questionThumb.setUserId(userId);
        questionThumb.setQuestionId(questionId);
        QueryWrapper<QuestionThumb> thumbQueryWrapper = new QueryWrapper<>(questionThumb);
        QuestionThumb oleQuestionThumb = this.getOne(thumbQueryWrapper);

        boolean result;
        //用户已点赞
        if (oleQuestionThumb != null) {
            result = this.remove(thumbQueryWrapper);
            if (result){
                //点赞数-1
                result = questionService.update()
                        .eq("id",questionId)
                        .gt("thumbNum",0)
                        .setSql("thumbNum = thumbNum - 1")
                        .update();
                return result ? -1 : 0;
            }
            else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        //未点赞
        else {
            result = this.save(questionThumb);
            if(result){
                result = questionService.update()
                        .eq("id",questionId)
                        .setSql("thumbNum = thumbNum + 1")
                        .update();
                return result ? 1 : 0;
            }
            else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }


}
